package com.example.lushudao_admin.controller;

import com.example.lushudao_admin.entity.Admin;
import com.example.lushudao_admin.mapper.AdminMapper;
import com.example.lushudao_admin.service.impl.AdminServiceImpl;
import com.example.lushudao_admin.utils.Md5Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@Controller
public class AdminController {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AdminServiceImpl adminService;

    @GetMapping("/{url}")
    public String redirect(@PathVariable("url") String url) {
        return url;
    }

    @GetMapping("favicon.ico")
    @ResponseBody
    void returnNoFavicon() {
    }

    @GetMapping("/userList/limit/{page}")
    @ResponseBody
    public Map<String, Object> getUserListLimit(@PathVariable(value = "page") int page) {
        int start = (page - 1) * 10;
        String userList = adminMapper.getUserLimit(start, 10).toString();
        String userList2 = redisTemplate.opsForValue().get("userList" + start + "/10");
        Map<String, Object> res = new HashMap<>();
        int listCount = adminMapper.selectUserPageCount().getId();
        if (userList2 == null) {
            redisTemplate.opsForValue().set("userList" + start + "/10", userList);
            res.put("result", adminMapper.getUserLimit(start, 10).toString());
            res.put("page", PageUtils(listCount));
            return res;
        } else {
            res.put("result", redisTemplate.opsForValue().get("userList" + start + "/10"));
            res.put("page", PageUtils(listCount));
            return res;
        }
    }


    @GetMapping("/userReleaseList/limit/{page}")
    @ResponseBody
    public Map<String, Object> getUserReleaseListLimit(@PathVariable(value = "page") int page) {
        int start = (page - 1) * 10;
        String userReleaseList = adminMapper.userReleaseList(start, 10).toString();
        String userReleaseList2 = redisTemplate.opsForValue().get("userReleaseList" + start + "/10");
        Map<String, Object> res = new HashMap<>();
        int listCount = adminMapper.selectScenicRelaseListPageCount().getId();
        if (userReleaseList2 == null) {
            redisTemplate.opsForValue().set("userReleaseList" + start + "/10", userReleaseList);
            res.put("result", adminMapper.userReleaseList(start, 10).toString());
            res.put("page", PageUtils(listCount));
            return res;
        } else {
            res.put("result", redisTemplate.opsForValue().get("userReleaseList" + start + "/10"));
            res.put("page", PageUtils(listCount));
            return res;
        }
    }


    @GetMapping("/scenicList/limit/{page}")
    @ResponseBody
    public Map<String, Object> getScenicListLimit(@PathVariable(value = "page") int page) {
        int start = (page - 1) * 10;
        String scenicList = adminMapper.scenicList(start, 10).toString();
        String scenicList2 = redisTemplate.opsForValue().get("scenicList" + start + "/10");
        Map<String, Object> res = new HashMap<>();
        int listCount = adminMapper.selectScenicListPageCount().getId();
        if (scenicList2 == null) {
            redisTemplate.opsForValue().set("scenicList" + start + "/10", scenicList);
            res.put("result", adminMapper.scenicList(start, 10).toString());
            res.put("page", PageUtils(listCount));
            return res;
        } else {
            res.put("result", redisTemplate.opsForValue().get("scenicList" + start + "/10"));
            res.put("page", PageUtils(listCount));
            return res;
        }
    }


    @GetMapping("/userCommentList/limit/{page}")
    @ResponseBody
    public Map<String, Object> getUserCommentListLimit(@PathVariable(value = "page") int page) {
        int start = (page - 1) * 10;
        String userCommentList = adminMapper.userCommentList(start, 10).toString();
        String userCommentList2 = redisTemplate.opsForValue().get("userCommentList" + start + "/10");
        Map<String, Object> res = new HashMap<>();
        int listCount = adminMapper.selectUserCommentPageCount().getId();
        if (userCommentList2 == null) {
            redisTemplate.opsForValue().set("userCommentList" + start + "/10", userCommentList);
            res.put("result", adminMapper.userCommentList(start, 10).toString());
            res.put("page", PageUtils(listCount));
            return res;
        } else {
            res.put("result", redisTemplate.opsForValue().get("userCommentList" + start + "/10"));
            res.put("page", PageUtils(listCount));
            return res;
        }
    }


    @GetMapping("/infoManageList/limit/{page}")
    @ResponseBody
    public Map<String, Object> getinfoManageListListLimit(@PathVariable(value = "page") int page) {
        int start = (page - 1) * 10;
        String infoManageList = adminMapper.infoManageList(start, 10).toString();
        String infoManageList2 = redisTemplate.opsForValue().get("manageListInfo" + start + "/10");
        Map<String, Object> res = new HashMap<>();
        int listCount = adminMapper.selectInfoAdminPageCount().getId();
        if (infoManageList2 == null) {
            redisTemplate.opsForValue().set("manageListInfo" + start + "/" + 10, infoManageList);
            res.put("result", adminMapper.infoManageList(start, 10).toString());
            res.put("page", PageUtils(listCount));
            return res;
        } else {
            res.put("result", redisTemplate.opsForValue().get("manageListInfo" + start + "/10"));
            res.put("page", PageUtils(listCount));
            return res;
        }
    }

    @GetMapping("/delect/{method}/{id}")
    @ResponseBody
    public void delect(@PathVariable(value = "id") int id, @PathVariable(value = "method") String method) {
        System.out.println(method + "_" + id);
        switch (method) {
            case "delectUserComment":
                adminService.delectUserComment(id);
                break;
            case "delectUserRelease":
                adminService.delectUserRelease(id);
                break;
            case "delectUser":
                adminService.delectUser(id);
                break;
            case "delectScenic":
                adminService.delectScenic(id);
                break;
            case "delectAdmin":
                adminService.delectAdmin(id);
                break;
            default:
                System.out.println("未执行删除");
        }

    }
//    @GetMapping("/delect/delectUserRelease/{scenic_release_id}")
//    @ResponseBody
//    public void delectUserRelease(@PathVariable int scenic_release_id) {
//        adminService.delectUserRelease(scenic_release_id);
//    }
//    @GetMapping("/delectUser/{user_id}")
//    @ResponseBody
//    public void delectUser(@PathVariable int user_id) {
//        adminService.delectUser(user_id);
//    }
//    @GetMapping("/delectScenic/{scenic_id}")
//    @ResponseBody
//    public void delectScenic(@PathVariable int scenic_id) {
//        adminService.delectScenic(scenic_id);
//    }
//    //    void delectAdmin(int admin_id);
//    @GetMapping("/delectAdmin/{admin_id}")
//    @ResponseBody
//    public void delectAdmin(@PathVariable int admin_id) {
//        adminService.delectAdmin(admin_id);
//    }

    //    selectSystemAdminPageCount
    @GetMapping("/stytemManageList/limit/{page}")
    @ResponseBody
    public Map<String, Object> getstytemManageListLimit(@PathVariable(value = "page") int page) {
        int start = (page - 1) * 10;
        String stytemManageList = adminMapper.stytemManageList(start, 10).toString();
        String stytemManageList2 = redisTemplate.opsForValue().get("manageListStytem" + start + "/10");
        Map<String, Object> res = new HashMap<>();
        int listCount = adminMapper.selectSystemAdminPageCount().getId();
        if (stytemManageList2 == null) {
            redisTemplate.opsForValue().set("manageListstytem" + start + "/" + 10, stytemManageList);
            res.put("result", adminMapper.stytemManageList(start, 10).toString());
            res.put("page", PageUtils(listCount));
            return res;
        } else {
            res.put("result", redisTemplate.opsForValue().get("manageListStytem" + start + "/10"));
            res.put("page", PageUtils(listCount));
            return res;
        }
    }


    @PostMapping("/update")
    public String updateAdmin( Model model,@RequestParam("admin_id") int admin_id, @RequestParam("admin_name") String admin_name, @RequestParam("admin_login") String admin_login, @RequestParam("admin_pass_new") String admin_pass_new) throws Exception {

        adminService.updateAdmin(admin_id, admin_name,admin_login, Md5Util.encodeByMd5(admin_pass_new));
        return "update";
    }

    @GetMapping("/admin/id={admin_id}")
    @ResponseBody
    public String findOneAdmin(@PathVariable int admin_id) {
        String adminOne = adminMapper.findOneAdmin(admin_id).toString();
        String str = "roam_admin" + String.valueOf(admin_id);
        String audioList2 = redisTemplate.opsForValue().get(str);
        if (audioList2 == null) {
            redisTemplate.opsForValue().set(str, adminOne);
            return adminMapper.findOneAdmin(admin_id).toString();
        } else {
            return redisTemplate.opsForValue().get(str);
        }
    }


    @PostMapping("/login")
    public String login(String adminlogin, String adminpass, HttpServletRequest httpServletRequest, Model model) throws Exception {
        Subject subject = SecurityUtils.getSubject();

        //使用工具库后
        UsernamePasswordToken token = new UsernamePasswordToken(adminlogin, Md5Util.encodeByMd5(adminpass));
        try {
            subject.login(token);
            Admin admin = (Admin) subject.getPrincipal();
            subject.getSession().setAttribute("admin", admin);
            return "index";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg", "用户名错误");
            e.printStackTrace();
            return "login";
        } catch (IncorrectCredentialsException e) {
            model.addAttribute("msg", "密码错误");
            e.printStackTrace();
            return "login";
        }

    }
//    @GetMapping("/page")
//    public Map<String, Object> findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize){
//        pageNum = （pageNum-1)*pageSize;
//        List<User> data = userMapper.selectPage(pageNum,pageSize);
//        Integer total = userMapper.selectTotal();
//        Map<String,Object> res = new HashMap<>();
//        res.put("data",data);
//        res.put("total",total);
//        return res;
//}

    @GetMapping("/unauthor")
    @ResponseBody
    public String unauthor() {
        return "未授权，无法访问！";
    }

    @GetMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }

    public Map<String, Object> PageUtils(int listCount) {
        int pageCount = listCount / 10 + 1;
        Map<String, Object> res = new HashMap<>();
        res.put("listCount", listCount);
        res.put("pageCount", pageCount);
        return res;
    }


}
